import os
import json
import shutil


# def move_FoV_files(path):
#     os.makedirs('./FoV', exist_ok=True)
#     origin_files = os.listdir(path)
#     for file in origin_files:
#         if not os.path.isdir(file):
#             shutil.copy(path + file + '/posCoordinates.json', './FoV/' + file + '_posCoordinates.json')


# def move_throughput_files(path):
#     os.makedirs('./Network_throughput', exist_ok=True)
#     origin_files = os.listdir(path)
#     for file in origin_files:
#         if not os.path.isdir(file):
#             shutil.copy(path + file + '/throughput.txt', './Network_throughput/' + file + '_throughput.csv')


# def move_delay_files(path):
#     os.makedirs('./Delay', exist_ok=True)
#     origin_files = os.listdir(path)
#     for file in origin_files:
#         if not os.path.isdir(file):
#             shutil.copy(path + file + '/m4sDelay.json', './Delay/' + file + '_delay.json')


def move_dir(p1, p2):
    """
    从FTP服务器指定文件夹移动数据集
    :param p1: 原始路径
    :param p2: 目标路径
    :return: null
    """
    os.makedirs(p2, exist_ok=True)
    dirs = os.listdir(p1)
    for d in dirs:
        # print(os.path.isdir(p2 + d))
        if not os.path.isdir(p2 + d):
            # os.makedirs(p2 + d, exist_ok=True)
            shutil.copytree(p1 + d, p2 + d)
            print('Moving directory: ' + d)


def cook_fov_throughput(path, movie):
    """
    数据预处理，删除多余长度的数据，将网络吞吐量、FoV信息保存至对应文件夹
    :param path:待处理的目录
    :param movie: 待命名的电影名
    :return: null
    """
    dirs = os.listdir(path)
    for d in dirs:
        if os.path.isfile('./FoV/' + d + '_fov.txt') and os.path.isfile('./Network_throughput/' + d + '_network.txt'):
            print(d + ' has been processed before')
            continue
        throughput_tmp = []

        # buffer
        # buffer_tmp = []
        # with open(path + d + '/buffer.txt', 'r') as f3:
        #     while True:
        #         line = f3.readline()
        #         if not line or ('NaN' in line):
        #             break
        #         tmp = [round(float(i), 3) for i in line.split(',')]
        #         buffer_tmp.append(tmp)

        # throughput
        with open(path + d + '/throughput.txt', 'r') as f1:
            while True:
                line = f1.readline()
                if not line:
                    break
                tmp = [format(float(i), '.2f') for i in line.split(',')]
                throughput_tmp.append(tmp)
        # 删除结尾多余记录
        time_count = len(throughput_tmp)
        for i in range(len(throughput_tmp)-2, -1, -1):
            if throughput_tmp[i] == tmp:
                time_count -= 1
            else:
                break

        # bitrate level index
        # with open(path + d + '/bitrateLevel.txt', 'r') as f2:
        #     while True:
        #         line = f2.readline()
        #         if not line:
        #             break
        #         tmp = [int(i) for i in line.split(',')]
        #         quality_tmp.append(tmp)

        # FoV
        with open(path + d + '/posCoordinates.json', 'r') as f4:
            fov_tmp = json.load(f4)

        if 4*time_count > len(fov_tmp):
            print('Length not correct in ' + d)
            continue

        os.makedirs('./FoV/', exist_ok=True)
        with open('./FoV/' + movie + '_' + d + '_fov.txt', 'w') as write_file_1:
            for i in range(time_count):
                write_file_1.write(fov_tmp[4*i]['time'] + ',' + format(float(fov_tmp[4*i]['x'])/720, '.4f') + ','
                                   + format(float(fov_tmp[4*i]['y'])/720, '.4f') + ','
                                   + format(float(fov_tmp[4*i]['z'])/720, '.4f') + '\n')
                # print(type(fov_tmp[4*i]['x']))
        print('Successfully process FoV info in ' + d)

        os.makedirs('./Network_throughput/', exist_ok=True)
        with open('./Network_throughput/' + movie + '_' + d + '_network.txt', 'w') as write_file_2:
            for i in range(time_count):
                write_file_2.write(str(i) + ',' + ','.join(throughput_tmp[i]) + '\n')
        print('Successfully process throughput info in ' + d)


if __name__ == '__main__':
    path_loc = '../raw_data/from_the_system/'
    path = 'D:/ftp/VR_dataset/VR_dataset_2021-12-08/'

    # move to ./raw_data
    # move_dir(path, path_loc)

    # process in row data
    cook_fov_throughput(path_loc, 'BG')

    # sort the files
    # move_FoV_files(path_loc)
    # move_throughput_files(path_loc)
    # move_delay_files(path_loc)
